package pl.edu.mimuw.mas.agent.behaviour;

import jade.core.Agent;
import jade.core.behaviours.Behaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

import java.util.List;

public class ReplyWaitingBehaviour extends Behaviour {

	private static final long serialVersionUID = 8075677708483975042L;
	
	private long finishTime;
	private MessageTemplate mt;
	private List<ACLMessage> replies; 
	
	private boolean finished = false;
	
	public ReplyWaitingBehaviour(Agent a, MessageTemplate mt, long waitPeriod, List<ACLMessage> replies) {
		this.mt = mt;

		this.replies = replies;
		
		finishTime = System.currentTimeMillis() + waitPeriod;
	}

	@Override
	public void action() {
		ACLMessage reply = myAgent.receive(mt);
		
		long timeToGo = finishTime - System.currentTimeMillis();
		
		// zapamiętuję wiadomość
		if (reply != null) {
			replies.add(reply);
		}
		
		// sprawdzam czy muszę jeszcze czekać
		if (timeToGo > 0) {
			block(timeToGo);
		} else {
			finished = true;
		}
	}
	
	public List<ACLMessage> getReplies() {
		return replies;
	}

	@Override
	public boolean done() {
		return finished;
	}

}
